<script setup lang="ts">
import { BaseApi } from "@/apis/base.api";
import { UtilTool } from "@webxue/common";
import useForm from "@/hooks/useForm";
import useCusRouter from "@/hooks/useCusRouter";
import EventEmitTool from "@/utils/tools/event-emit.tool";
import { onMounted, reactive } from "vue";
import { useWebxRouteTabs } from "@webxue/vue3-antdv-ui";
import IconList from "../icon/Components/IconList.vue";

// 获取路由属性
const { router, routeQuery } = useCusRouter({
  queryKeys:[
    // 菜单id
    "menuId",
    // 是否只读
    "readonly",
    // 父级id
    "pId"
  ]
});
const { addParentTab } = useWebxRouteTabs({ router });
// 获取详情hook
const { detailInfo, formRef, formState, onValidateFields, getFormRules } = useForm({
  // 获取表单数据
  formState: {} as Record<string, any>,
  // 获取详情数据
  async onInit() {
    // 数据初始化
    formState.value.status = 1;

    // 添加子级
    if(routeQuery.value.pId) {
      formState.value.parentId = routeQuery.value.pId;
    }

    // 设置默认排序号
    const nextSortRes = await BaseApi.menu.getNextSort({ parentId: routeQuery.value.pId });
    formState.value.sort = nextSortRes.data;

    // 获取详情
    if (!routeQuery.value.menuId) return false;
    const response = await BaseApi.menu.find({ id: routeQuery.value.menuId });
    // 数据回显
    formState.value = UtilTool.lodash.cloneDeep(response.data);
    return Promise.resolve(response);
  },
  // 表单校验成功回调
  async onValidateSuccess(values) {
    // 响应结果
    let response: Partial<ResponseData> = {};
    // 请求参数
    const requestBody: Record<string, any> = {
      name: values.name,
      path: values.path,
      parentId: values.parentId,
      icon: values.icon,
      remark: values.remark,
      showMenu: values.showMenu,
      isCommon: values.isCommon,
      sort: values.sort,
    };
    if (routeQuery.value.menuId) {
      // 编辑
      response = await BaseApi.menu.update({
        ...requestBody,
        id: routeQuery.value.menuId
      });
    } else {
      // 新增
      response = await BaseApi.menu.save({
        ...requestBody
      });
    }
    if(response.success) {
      addParentTab();
    }
  }
});
// 获取节点树
const menuTree = reactive({
  dataSource:[],
  async setDataSource(){
    const response = await BaseApi.menu.tree();
    menuTree.dataSource = response.data;
  }
})
// 选择图标结束回调
function getSelectIcon(icon:any, closeModal?:() => void){
  formState.value.icon = `${icon.from}:${icon.className}`;
  closeModal?.();
}

// form保存回调
EventEmitTool.on("FORM:SAVE", () => {
  // 开始校验
  onValidateFields();
});

onMounted(async () => {
  await menuTree.setDataSource();
})
</script>

<template>
  <div>
    <WebxForm ref="formRef" :model="formState" :readonly="!!routeQuery.readonly">
      <div class="flex flex-col gap-2">
        <WebxCard :titleProps="{ title:'菜单维护' }">
          <ARow class="px-2 pb-4" :gutter="10">
            <ACol :span="8">
              <WebxFormItem label="上级菜单" name="parentId">
                <ATreeSelect
                    v-model:value="formState.parentId"
                    style="width: 100%"
                    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                    placeholder="请选择上级菜单"
                    allowClear
                    :fieldNames="{ children:'children', label:'name', value:'id' }"
                    :treeData="menuTree.dataSource"
                />
                <template #readonly>{{ formState.parentId }}</template>
              </WebxFormItem>
            </ACol>
            <ACol :span="8">
              <WebxFormItem label="菜单名称" name="name" :rules="[{ required: true, message:'请输入菜单名称' }]">
                <AInput v-model:value="formState.name" placeholder="请输入菜单名称" />
                <template #readonly>{{ formState.name }}</template>
              </WebxFormItem>
            </ACol>
            <ACol :span="8">
              <WebxFormItem label="路径" name="path">
                <AInput v-model:value="formState.path" placeholder="请输入路径" />
                <template #readonly>{{ formState.path }}</template>
              </WebxFormItem>
            </ACol>
            <ACol :span="8">
              <WebxFormItem label="排序号" name="sort">
                <AInput v-model:value="formState.sort" placeholder="请输入排序号" />
                <template #readonly>{{ formState.sort }}</template>
              </WebxFormItem>
            </ACol>
            <ACol :span="8">
              <WebxFormItem label="侧边展示" name="showMenu">
                <ARadioGroup v-model:value="formState.showMenu">
                  <ARadio :value="1">显示</ARadio>
                  <ARadio :value="0">隐藏</ARadio>
                </ARadioGroup>
                <template #readonly>{{ formState.showMenu }}</template>
              </WebxFormItem>
            </ACol>
            <ACol :span="8">
              <WebxFormItem label="公共菜单" name="isCommon" tooltip="当前菜单对所有用户开放">
                <ARadioGroup v-model:value="formState.isCommon">
                  <ARadio :value="1">是</ARadio>
                  <ARadio :value="0">否</ARadio>
                </ARadioGroup>
                <template #readonly>{{ formState.isCommon }}</template>
              </WebxFormItem>
            </ACol>
            <ACol :span="8">
              <WebxFormItem label="图标" name="icon">
                <WebxInputModal v-model:value="formState.icon" placeholder="请选择图标" :modalProps="{ title:'选择图标', width:'70vw', footer: false }">
                  <template #suffix>
                    <WebxIcon class="text-xl" :name="formState.icon || ''" />
                  </template>
                  <template #modal="{ closeModal }">
                    <div class="h-[600px] overflow-y-auto">
                      <IconList :colCount="5" @select="(icon) => getSelectIcon(icon, closeModal)" />
                    </div>
                  </template>
                </WebxInputModal>
              </WebxFormItem>
            </ACol>
            <ACol :span="24">
              <WebxFormItem label="备注" name="remark">
                <ATextarea v-model:value="formState.remark" placeholder="请输入备注" :autoSize="{ minRows: 4, maxRows: 4 }" />
                <template #readonly>{{ formState.remark }}</template>
              </WebxFormItem>
            </ACol>
          </ARow>
        </WebxCard>
      </div>
    </WebxForm>
  </div>
</template>

<style scoped lang="less">
.ant-form-item {
  margin-bottom: 0;
  :deep(.ant-form-item-label){
    width: 120px;
  }
}
</style>
